import {
  DndContext,
  DragEndEvent,
  KeyboardSensor,
  PointerSensor,
  closestCenter,
  useSensor,
  useSensors,
} from '@dnd-kit/core'
import {
  SortableContext,
  arrayMove,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import React, { useState } from 'react'
import Item from './Item'

type ComponentType = {
  fe_id: string
  title: string
}

function DndKitDemo() {
  // const [items, setItems] = useState(['a', 'b', 'c'])
  const [items, setItems] = useState<ComponentType[]>([
    { fe_id: 'c1', title: '组件1' },
    { fe_id: 'c2', title: '组件2' },
    { fe_id: 'c3', title: '组件3' },
  ])

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  )

  function handleDragEnd({ active, over }: DragEndEvent) {
    if (over == null) return
    if (active.id !== over.id) {
      setItems(items => {
        // const oldIndex = items.indexOf(active.id.toString())
        // const newIndex = items.indexOf(over.id.toString())

        const oldIndex = items.findIndex(c => c.fe_id === active.id)
        const newIndex = items.findIndex(c => c.fe_id === over.id)
        return arrayMove(items, oldIndex, newIndex)
      })
    }
  }

  const itemsWithId = items.map(item => ({ ...item, id: item.fe_id }))
  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={itemsWithId} strategy={verticalListSortingStrategy}>
        {itemsWithId.map(c => (
          <Item key={c.id} id={c.id} title={c.title}></Item>
        ))}
      </SortableContext>
    </DndContext>
  )
}

export default DndKitDemo
